<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <!-- 左侧显示记录条数 -->
        <template v-slot:before>
          <span>共{{ total }}条记录</span>
        </template>
        <!-- 右侧显示按钮 - excel导入导出 新增员工 -->
        <template v-slot:after>
          <el-button type="success" size="small" @click="excelImport">excel导入</el-button>
          <el-button type="danger" size="small" @click="exportData">excel导出</el-button>
          <el-button type="primary" size="small" @click="addEmployee">新增员工</el-button>
        </template>
      </PageTools>
      <el-card>
        <el-table v-loading="loading" border :data="list">
          <el-table-column label="序号" sortable="" type="index" align="center" />
          <el-table-column label="姓名" sortable="" prop="username" align="center" />
          <el-table-column label="头像" align="center">
            <template v-slot="{ row }">
              <img v-imagerror="require('@/assets/common/head.jpg')" :src="row.staffPhoto" style="border-radius: 50%; width: 100px; height: 100px; padding: 10px" @click="showQrCode(row)">
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" align="center" />
          <el-table-column label="聘用形式" sortable="" :formatter="formatEmployment" prop="formOfEmployment" align="center" />
          <el-table-column label="部门" sortable="" prop="departmentName" align="center" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry" align="center" />
          <el-table-column label="账户状态" sortable="" prop="" align="center" />
          <el-table-column label="操作" sortable="" fixed="right" width="280" align="center">
            <template slot-scope="{ row }">
              <el-button type="text" size="small" @click="$router.push(`employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px;">
          <el-pagination
            layout="prev, pager, next"
            :total="total"
            :current-page="params.page"
            :page-size="params.size"
            @current-change="changePage"
          />
        </el-row>

      </el-card>
      <!-- 新增员工弹窗 -->
      <AddEmployee :show-dialog.sync="showDialog" />

      <el-dialog title="二维码" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center" align="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <!-- 角色分配弹窗 -->
      <AssginRole ref="AssginRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import employEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee.vue'
import { formatDate } from '@/utils/filters'
import QrCode from 'qrcode'
// 角色分配组件
import AssginRole from './components/assign-role.vue'
export default {
  name: 'EmployeesIndex',
  components: {
    AddEmployee,
    AssginRole
  },
  data() {
    return {
      list: [], // 存储员工列表
      params: { // 获取员工列表要传的参数
        page: 1, // 页码
        size: 10 // 每页条数
      },
      total: 0, // 员工列表数据条数
      loading: false, // 当数据在加载时的遮罩
      showDialog: false, // 显示新增员工弹窗
      showCodeDialog: false, // 控制二维码弹层显示
      showRoleDialog: false, // 控制角色分配弹窗
      userId: '' // 角色分配所需员工id
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      this.loading = true
      try {
        const { total, rows } = await getEmployeeList(this.params)
        this.total = total
        this.list = rows
      } catch (error) {
        console.log(error)
      }
      this.loading = false
    },
    // 分页器 页数改变回调函数
    changePage(currentPage) {
      this.params.page = currentPage
      this.getEmployeeList() // 重新拉取数据
    },
    formatEmployment(row, column, cellValue, index) {
      // console.log(row, column, cellValue, index)
      const obj = employEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    // 删除员工
    async delEmployee(id) {
      try {
        await this.$confirm('您确定删除员工？')
        await delEmployee(id)
        // 重新拉取数据
        this.getEmployeeList()
        this.$message.success('删除成功')
      } catch (error) {
        console.log(error)
      }
    },
    addEmployee() {
      this.showDialog = true
    },
    // excel导入员工
    excelImport() {
      this.$router.push('/import')
    },
    async exportData() {
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const { rows } = await getEmployeeList({ page: 1, size: this.total })
      const data = this.formatJson(headers, rows)
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          multiHeader,
          merges,
          filename: '员工资料表'
        })
      })
    },
    formatJson(headers, rows) {
      return rows.map(item => {
        return Object.keys(headers).map(ckey => {
          // 通过中文名找英文名 => 找到对应值
          // 用遍历数组的方式固定数组元素顺序
          if (headers[ckey] === 'correctionTime' || headers[ckey] === 'timeOfEntry') {
            return formatDate(item[headers[ckey]])
          } else if (headers[ckey] === 'formOfEmployment') {
            const obj = employEnum.hireType.find(obj => obj.id === item[headers[ckey]])
            return obj ? obj.value : '未知'
          }
          return item[headers[ckey]]
        })
      })
      // return rows.map(item => Object.keys(headers).map(ckey => item[headers[ckey]]))
    },
    // 二维码
    showQrCode(url) {
      if (url) {
        this.showCodeDialog = true
        // this.showDialog = true

        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.myCanvas, url.staffPhoto)
        })
      } else {
        this.$message.warning('该员工未上传头像')
      }
    },
    // 点击角色的回调函数
    async editRole(id) {
      await this.$refs.AssginRole.getUserDetailById(id)
      this.showRoleDialog = true
      this.userId = id
    }
  }
}
</script>

<style>

</style>
